package com.witdata.framework.service.code.impl;

import com.alibaba.fastjson2.JSON;
import com.mybatisflex.core.query.QueryWrapper;
import com.witdata.mysql.base.service.EnvironmentBaseService;
import com.witdata.common.domain.Status;
import com.witdata.common.domain.dto.EnvironmentDto;
import com.witdata.mysql.domain.entity.TEnvironment;
import com.witdata.common.exception.GlobalException;
import com.witdata.common.mapper.EnvironmentMapper;
import com.witdata.common.util.IdUtils;
import com.witdata.framework.service.code.EnvironmentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class EnvironmentServiceImpl implements EnvironmentService {
    private final EnvironmentBaseService environmentBaseService;

    @Override
    public List<EnvironmentDto> getEnvironmentList() {
        List<TEnvironment> tEnvironmentList = environmentBaseService.list();
        return EnvironmentMapper.INSTANCE.toEnvironmentDtoList(tEnvironmentList);
    }

    @Override
    public void createEnvironment(EnvironmentDto environmentDto) {
        TEnvironment tEnvironment = EnvironmentMapper.INSTANCE.toTEnvironment(environmentDto);
        if (environmentDto.getContainerEnv() != null) {
            List<String> containerEnv = environmentDto.getContainerEnv();
            List<String> data = containerEnv.stream().filter(StringUtils::hasText).toList();
            String jsonString = JSON.toJSONString(data);
            tEnvironment.setContainerEnv(jsonString);
        }
        tEnvironment.setId(IdUtils.createId());
        boolean exists = environmentBaseService.exists(new QueryWrapper().eq("name", tEnvironment.getName()));
        if (exists) throw new GlobalException(Status.ISEXISTS);
        boolean save = environmentBaseService.save(tEnvironment);
        if (!save) throw new GlobalException(Status.CREATEERROR);
    }

    @Override
    public EnvironmentDto getEnvironmentById(Long id) {
        TEnvironment tEnvironment = environmentBaseService.getOne(new QueryWrapper().eq("id", id));
        return EnvironmentMapper.INSTANCE.toEnvironmentDto(tEnvironment);
    }

}
